package com.addplus.townmall.server.queue_consumer.consumer;

import com.addplus.townmall.server.api.constant.StringConstant;
import com.addplus.townmall.server.api.mapper.town.*;
import com.addplus.townmall.server.api.model.town.*;
import com.addplus.townmall.server.api.model.town.param.AliPayNotifyParam;
import com.addplus.townmall.server.api.model.town.param.ShopProductStockManagerParam;
import com.addplus.townmall.server.api.mongodao.AliPayOrderNotifyResultExpandDao;
import com.addplus.townmall.server.api.mongodao.ShopSkuModelDao;
import com.addplus.townmall.server.api.mongodao.WxPayOrderNotifyResultExpandDao;
import com.addplus.townmall.server.api.utils.DataUtils;
import com.addplus.townmall.server.api.utils.date.DateUtils;
import com.addplus.townmall.server.connector.redis.RedisSlaveTemplateManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 类名: ShopProductStockManagerConsumer
 *
 * @author zhangjiehang
 * @version V1.0
 * @date 2018/10/7 下午4:27
 * @description 类描述: 商品库存加减消费队列
 */
@Component
@RabbitListener(queues = "fight_stock_manager_queue")
public class ShopProductFightManagerConsumer {

    private Logger logger = LoggerFactory.getLogger(ShopProductFightManagerConsumer.class);


    @Autowired
    private ShopSpecificationSkuMapper specificationSkuMapper;

    @Autowired
    private ShopProductFightMapper shopProductFightMapper;

    @Autowired
    private TownOrderFightMapper orderFightMapper;

    @Autowired
    private OrderItemsFightMapper orderItemsMapper;

    @Autowired
    private ShopSkuModelDao shopSkuModelDao;

    @Autowired
    private RedisSlaveTemplateManager templateManager;

    @Autowired
    private OrderPayMapper orderPayMapper;

    @Autowired
    private GiftMemberCardMapper giftMemberCardMapper;

    @Autowired
    private GiftMemberCardRecordMapper memberCardRecordMapper;

    @Autowired
    private WxPayOrderNotifyResultExpandDao wxPayOrderNotifyResultDao;

    @Autowired
    private AliPayOrderNotifyResultExpandDao aliPayOrderNotifyResultExpandDao;

    @RabbitHandler
    @Transactional(rollbackFor = Exception.class)
    public void process(ShopProductStockManagerParam stockManagerParam) throws IOException {
        if (stockManagerParam == null) {
            logger.error("stockManagerParam 入参参数为null");
            return;
        }
        //处理订单减库存
        if (stockManagerParam.getType() == 1) {
            orderFightStock(stockManagerParam);
        } else if (stockManagerParam.getType() == 2) {
            orderFightTimeOut(stockManagerParam);
        } else if (stockManagerParam.getType() == 3) {
            orderFightFailure(stockManagerParam);
        } else if (stockManagerParam.getType() == 4) {
            this.weChatFightSuccessNotify(stockManagerParam);
        } else if (stockManagerParam.getType() == 5) {
            this.aliPayFightSuccessNotify(stockManagerParam);
        } else {
            logger.error("stockManagerParam 类型错误,数据未：" + JSON.toJSONString(stockManagerParam));
        }
        logger.info("拼团订单消息记录：" + JSON.toJSONString(stockManagerParam));
    }

    private void aliPayFightSuccessNotify(ShopProductStockManagerParam stockManagerParam) {
        if (DataUtils.isEmptyObject(stockManagerParam)) {
            logger.error("入参参数为空");
        }
        AliPayNotifyParam aliPayNotifyParam = JSONObject.parseObject(stockManagerParam.getAliPayNotifyMsg(), AliPayNotifyParam.class);
        aliPayOrderNotifyResultExpandDao.insert(aliPayNotifyParam);
        if (aliPayNotifyParam == null) {
            logger.error("订单支付回调，获取回调信息为空，回调信息：" + stockManagerParam.getAliPayNotifyMsg());
            return;
        }
        String orderNum = aliPayNotifyParam.getOutTradeNo();
        // 查询当前订单
        QueryWrapper<TownOrderFight> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_number", orderNum);
        orderQueryWrapper.eq("is_delete", 0);
        TownOrderFight townOrder = orderFightMapper.selectOne(orderQueryWrapper);
        if (townOrder == null) {
            logger.error("拼团订单支付回调，查询原有订单失败，订单号：" + aliPayNotifyParam.getOutTradeNo());
            return;
        } else {
            // 查询是否已经执行过了
            QueryWrapper<OrderPay> payQueryWrapper = new QueryWrapper<>();
            payQueryWrapper.eq("order_id", townOrder.getId());
            payQueryWrapper.eq("type", 2);
            int orderPayCount = orderPayMapper.selectCount(payQueryWrapper);
            if (orderPayCount > 0) {
                logger.error("订单支付回调，当前订单已经执行，订单号：" + aliPayNotifyParam.getOutTradeNo());
                return;
            }
            // 检查当前订单金额是否一致
            String totalAmountInt = townOrder.getPayAmount().toString();
            if (!totalAmountInt.equals(aliPayNotifyParam.getTotalAmount().toString())) {
                logger.error("订单支付回调，支付金额和入参金额不一致，订单号" + aliPayNotifyParam.getOutTradeNo());
                // 添加商城订单支付表
                OrderPay orderPay = new OrderPay();
                orderPay.setOrderId(townOrder.getId());
                orderPay.setType(2);
                orderPay.setPayTypeId(1);
                orderPay.setPayNumber(aliPayNotifyParam.getTradeNo());
                orderPay.setPayStatus(1);
                orderPay.setPayRemark("支付金额不一致");
                orderPay.setGmtCreate(new Date());
                orderPay.setGmtModified(new Date());
                orderPayMapper.insert(orderPay);
                return;
            }
        }
        Date date = new Date();
        if (StringConstant.ALIPAY_WAIT.equals(aliPayNotifyParam.getTradeStatus())) { // 交易创建，等待买家付款
            UpdateWrapper<TownOrderFight> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("pay_status", 2);
            updateWrapper.set("order_status", 1);
            updateWrapper.set("pay_type_id", 2);
            updateWrapper.set("pay_type_name", "ali");
            updateWrapper.set("pay_date", date);
            updateWrapper.set("pay_remark", aliPayNotifyParam.getTradeStatus() + ",交易创建，等待买家付款");
            updateWrapper.set("gmt_modified", date);
            updateWrapper.eq("id", townOrder.getId());
            orderFightMapper.update(new TownOrderFight(), updateWrapper);
            return;
        } else if (StringConstant.ALIPAY_CLOSED.equals(aliPayNotifyParam.getTradeStatus())) { // 未付款交易超时关闭，或支付完成后全额退款
            // 更改当前订单支付状态为失败
            UpdateWrapper<TownOrderFight> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("pay_status", 3);
            updateWrapper.set("order_status", 1);
            updateWrapper.set("close_reason", "订单支付失败");
            updateWrapper.set("pay_type_id", 2);
            updateWrapper.set("pay_type_name", "ali");
            updateWrapper.set("pay_date", date);
            updateWrapper.set("pay_remark", aliPayNotifyParam.getTradeStatus() + ",未付款交易超时关闭，或支付完成后全额退款");
            updateWrapper.set("gmt_modified", date);
            updateWrapper.eq("id", townOrder.getId());
            orderFightMapper.update(new TownOrderFight(), updateWrapper);
            return;
        } else if (StringConstant.ALIPAY_SUCCESS.equals(aliPayNotifyParam.getTradeStatus())) {
            if (townOrder.getGiftMemberCardId() != 0 && townOrder.getGiftCardAmount().compareTo(BigDecimal.ZERO) == 1) {
                //如果有礼品卡，则修改礼品卡状态
                UpdateWrapper<GiftMemberCard> cardUpdateWrapper = new UpdateWrapper<>();
                cardUpdateWrapper.setSql("gift_value_left = gift_value_left -" + townOrder.getGiftCardAmount());
                cardUpdateWrapper.set("gmt_modified", date);
                cardUpdateWrapper.eq("id", townOrder.getGiftMemberCardId());
                cardUpdateWrapper.notIn("gift_status", 0, 3);
                cardUpdateWrapper.ge("gift_value_left", townOrder.getGiftCardAmount());
                int giftCount = giftMemberCardMapper.update(new GiftMemberCard(), cardUpdateWrapper);
                if (giftCount <= 0) {
                    logger.error("订单支付回调，修改礼品卡失败，礼品卡金额不足,订单号：" + aliPayNotifyParam.getOutTradeNo());
                } else {
                    // 查询对应品卡
                    GiftMemberCard giftMemberCard = giftMemberCardMapper.selectById(townOrder.getGiftMemberCardId());
                    UpdateWrapper<GiftMemberCard> giftMemberCardUpdateWrapper = new UpdateWrapper<>();
                    if (giftMemberCard.getGiftValueLeft().compareTo(BigDecimal.ONE) <= 0) {
                        giftMemberCardUpdateWrapper.set("gift_status", 3);
                    } else {
                        if (giftMemberCard.getGiftStatus() == 1) {
                            giftMemberCardUpdateWrapper.set("gift_status", 2);
                        }
                    }
                    giftMemberCardUpdateWrapper.set("gmt_modified", date);
                    giftMemberCardUpdateWrapper.eq("id", giftMemberCard.getId());
                    giftMemberCardMapper.update(new GiftMemberCard(), giftMemberCardUpdateWrapper);
                    GiftMemberCardRecord giftMemberCardRecord = new GiftMemberCardRecord();
                    giftMemberCardRecord.setGiftMemberCardId(townOrder.getGiftMemberCardId());
                    giftMemberCardRecord.setMemberId(townOrder.getMemberId());
                    giftMemberCardRecord.setOrderType(2);
                    giftMemberCardRecord.setUseMemberId(giftMemberCard.getUseMemberId());
                    giftMemberCardRecord.setGiftCardId(giftMemberCard.getGiftBatchCardId());
                    giftMemberCardRecord.setOrderId(townOrder.getId());
                    giftMemberCardRecord.setOrderAmount(townOrder.getGiftCardAmount());
                    giftMemberCardRecord.setGiftValueLeft(giftMemberCard.getGiftValueLeft());
                    giftMemberCardRecord.setGiftValueNow(giftMemberCard.getGiftValueLeft());
                    giftMemberCardRecord.setGiftValueUse(giftMemberCard.getGiftValue().subtract(giftMemberCard.getGiftValueLeft()));
                    giftMemberCardRecord.setIsDelete(0);
                    giftMemberCardRecord.setGmtCreate(date);
                    giftMemberCardRecord.setGmtModified(date);
                    memberCardRecordMapper.insert(giftMemberCardRecord);
                }
            }
            // 修改对应订单状态
            // 更改当前订单未支付状态
            UpdateWrapper<TownOrderFight> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("pay_status", 4);
            updateWrapper.set("pay_type_id", 2);
            updateWrapper.set("pay_type_name", "ali");
            updateWrapper.set("pay_date", aliPayNotifyParam.getGmtCreate());
            updateWrapper.set("pay_remark", aliPayNotifyParam.getTradeStatus() + ",交易支付成功");
            updateWrapper.set("gateway_order_id", aliPayNotifyParam.getTradeNo());
            updateWrapper.set("gmt_modified", date);
            if (townOrder.getIsGroup() == 0) {
                updateWrapper.set("order_status", 5);
            } else {
                updateWrapper.set("order_status", 2);
            }
            updateWrapper.setSql("actual_pay_amount = total_amount");
            updateWrapper.eq("id", townOrder.getId());
            int updateCount = orderFightMapper.update(new TownOrderFight(), updateWrapper);
            if (updateCount <= 0) {
                logger.error("订单支付回调，修改状态失败，订单号：" + aliPayNotifyParam.getOutTradeNo());
                return;
            } else {
                ShopProductStockManagerParam shopProductStockManagerParam = new ShopProductStockManagerParam();
                shopProductStockManagerParam.setType(1);
                shopProductStockManagerParam.setOrderNum(townOrder.getOrderNumber());
                this.orderFightStock(shopProductStockManagerParam);
            }
        } else {
            return;
        }
        // 添加商城订单支付表
        OrderPay orderPay = new OrderPay();
        orderPay.setOrderId(townOrder.getId());
        orderPay.setType(2);
        orderPay.setPayTypeId(1);
        orderPay.setPayNumber(aliPayNotifyParam.getTradeNo());
        orderPay.setPayStatus(aliPayNotifyParam.getTradeStatus() == StringConstant.ALIPAY_SUCCESS ? 0 : 1);
//        orderPay.setPayRemark(aliPayNotifyParam.getReturnMsg());
        orderPay.setGmtCreate(new Date());
        orderPay.setGmtModified(new Date());
        orderPayMapper.insert(orderPay);
        logger.info("订单支付回调，正常完成，订单号：" + aliPayNotifyParam.getOutTradeNo());
    }

    private void weChatFightSuccessNotify(ShopProductStockManagerParam stockManagerParam) {
        WxPayOrderNotifyResult wxPayOrderNotifyResult = JSONObject.parseObject(stockManagerParam.getXmldata(), WxPayOrderNotifyResult.class);
        if (wxPayOrderNotifyResult == null) {
            wxPayOrderNotifyResultDao.insert(wxPayOrderNotifyResult);
            logger.error("拼团订单支付回调，获取回调信息为空，回调信息：" + stockManagerParam.getXmldata());
            return;
        }
        // 获取对应商品订单主键id
        Integer orderId = Integer.parseInt(wxPayOrderNotifyResult.getAttach());
        // 查询当前订单
        QueryWrapper<TownOrderFight> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("id", orderId);
        orderQueryWrapper.eq("is_delete", 0);
        TownOrderFight townOrder = orderFightMapper.selectOne(orderQueryWrapper);
        if (townOrder == null) {
            logger.error("拼团订单支付回调，查询原有订单失败，订单号：" + wxPayOrderNotifyResult.getAttach());
            return;
        } else {
            // 查询是否已经执行过了
            QueryWrapper<OrderPay> payQueryWrapper = new QueryWrapper<>();
            payQueryWrapper.eq("order_id", orderId);
            payQueryWrapper.eq("type", 2);
            int orderPayCount = orderPayMapper.selectCount(payQueryWrapper);
            if (orderPayCount > 0) {
                logger.error("订单支付回调，当前订单已经执行，订单号：" + wxPayOrderNotifyResult.getAttach());
                return;
            }
            // 检查当前订单金额是否一致
            Integer totalAmountInt = townOrder.getPayAmount().multiply(BigDecimal.valueOf(100)).intValue();
            if (!totalAmountInt.equals(wxPayOrderNotifyResult.getTotalFee())) {
                logger.error("订单支付回调，支付金额和入参金额不一致，订单号" + wxPayOrderNotifyResult.getAttach());
                // 添加商城订单支付表
                OrderPay orderPay = new OrderPay();
                orderPay.setOrderId(orderId);
                orderPay.setType(2);
                orderPay.setPayTypeId(1);
                orderPay.setPayNumber(wxPayOrderNotifyResult.getTransactionId());
                orderPay.setPayStatus(1);
                orderPay.setPayRemark("支付金额不一致");
                orderPay.setGmtCreate(new Date());
                orderPay.setGmtModified(new Date());
                orderPayMapper.insert(orderPay);
                return;
            }
        }
        Date date = new Date();
        if (StringConstant.WECHAT_FAIL.equals(wxPayOrderNotifyResult.getResultCode())) {
            // 更改当前订单支付状态为失败
            UpdateWrapper<TownOrderFight> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("pay_status", 3);
            updateWrapper.set("order_status", 6);
            updateWrapper.set("close_reason", "订单支付失败");
            updateWrapper.set("pay_type_id", 1);
            updateWrapper.set("pay_type_name", "wechat");
            updateWrapper.set("pay_date", date);
            updateWrapper.set("pay_remark", wxPayOrderNotifyResult.getErrCode() + "," + wxPayOrderNotifyResult.getErrCodeDes());
            updateWrapper.set("gmt_modified", date);
            updateWrapper.eq("id", orderId);
            orderFightMapper.update(new TownOrderFight(), updateWrapper);
            return;
        } else if (StringConstant.WECHAT_SUCCESS.equals(wxPayOrderNotifyResult.getResultCode())) {
            if (townOrder.getGiftMemberCardId() != 0 && townOrder.getGiftCardAmount().compareTo(BigDecimal.ZERO) == 1) {
                //如果有礼品卡，则修改礼品卡状态
                UpdateWrapper<GiftMemberCard> cardUpdateWrapper = new UpdateWrapper<>();
                cardUpdateWrapper.setSql("gift_value_left = gift_value_left -" + townOrder.getGiftCardAmount());
                cardUpdateWrapper.set("gmt_modified", date);
                cardUpdateWrapper.eq("id", townOrder.getGiftMemberCardId());
                cardUpdateWrapper.notIn("gift_status", 0, 3);
                cardUpdateWrapper.ge("gift_value_left", townOrder.getGiftCardAmount());
                int giftCount = giftMemberCardMapper.update(new GiftMemberCard(), cardUpdateWrapper);
                if (giftCount <= 0) {
                    logger.error("订单支付回调，修改礼品卡失败，礼品卡金额不足,订单号：" + wxPayOrderNotifyResult.getAttach());
                } else {
                    // 查询对应品卡
                    GiftMemberCard giftMemberCard = giftMemberCardMapper.selectById(townOrder.getGiftMemberCardId());
                    UpdateWrapper<GiftMemberCard> giftMemberCardUpdateWrapper = new UpdateWrapper<>();
                    if (giftMemberCard.getGiftValueLeft().compareTo(BigDecimal.ONE) <= 0) {
                        giftMemberCardUpdateWrapper.set("gift_status", 3);
                    } else {
                        if (giftMemberCard.getGiftStatus() == 1) {
                            giftMemberCardUpdateWrapper.set("gift_status", 2);
                        }
                    }
                    giftMemberCardUpdateWrapper.set("gmt_modified", date);
                    giftMemberCardUpdateWrapper.eq("id", giftMemberCard.getId());
                    giftMemberCardMapper.update(new GiftMemberCard(), giftMemberCardUpdateWrapper);
                    GiftMemberCardRecord giftMemberCardRecord = new GiftMemberCardRecord();
                    giftMemberCardRecord.setGiftMemberCardId(townOrder.getGiftMemberCardId());
                    giftMemberCardRecord.setMemberId(townOrder.getMemberId());
                    giftMemberCardRecord.setOrderType(2);
                    giftMemberCardRecord.setUseMemberId(giftMemberCard.getUseMemberId());
                    giftMemberCardRecord.setGiftCardId(giftMemberCard.getGiftBatchCardId());
                    giftMemberCardRecord.setOrderId(townOrder.getId());
                    giftMemberCardRecord.setOrderAmount(townOrder.getGiftCardAmount());
                    giftMemberCardRecord.setGiftValueLeft(giftMemberCard.getGiftValueLeft());
                    giftMemberCardRecord.setGiftValueNow(giftMemberCard.getGiftValueLeft());
                    giftMemberCardRecord.setGiftValueUse(giftMemberCard.getGiftValue().subtract(giftMemberCard.getGiftValueLeft()));
                    giftMemberCardRecord.setIsDelete(0);
                    giftMemberCardRecord.setGmtCreate(date);
                    giftMemberCardRecord.setGmtModified(date);
                    memberCardRecordMapper.insert(giftMemberCardRecord);
                }
            }
            // 修改对应订单状态
            // 更改当前订单未支付状态
            UpdateWrapper<TownOrderFight> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("pay_status", 4);
            updateWrapper.set("pay_type_id", 1);
            updateWrapper.set("pay_type_name", "wechat");
            updateWrapper.set("pay_date", wxPayOrderNotifyResult.getTimeEnd());
            updateWrapper.set("pay_remark", wxPayOrderNotifyResult.getReturnMsg());
            updateWrapper.set("gateway_order_id", wxPayOrderNotifyResult.getTransactionId());
            updateWrapper.set("gmt_modified", date);
            if (townOrder.getIsGroup() == 0) {
                updateWrapper.set("order_status", 5);
            } else {
                updateWrapper.set("order_status", 2);
            }
            updateWrapper.setSql("actual_pay_amount = total_amount");
            updateWrapper.eq("id", orderId);
            int updateCount = orderFightMapper.update(new TownOrderFight(), updateWrapper);
            if (updateCount <= 0) {
                logger.error("订单支付回调，修改状态失败，订单号：" + wxPayOrderNotifyResult.getAttach());
                return;
            } else {
                ShopProductStockManagerParam shopProductStockManagerParam = new ShopProductStockManagerParam();
                shopProductStockManagerParam.setType(1);
                shopProductStockManagerParam.setOrderNum(townOrder.getOrderNumber());
                this.orderFightStock(shopProductStockManagerParam);
            }
        } else {
            return;
        }
        // 添加商城订单支付表
        OrderPay orderPay = new OrderPay();
        orderPay.setOrderId(orderId);
        orderPay.setType(2);
        orderPay.setPayTypeId(1);
        orderPay.setPayNumber(wxPayOrderNotifyResult.getTransactionId());
        orderPay.setPayStatus(wxPayOrderNotifyResult.getResultCode() == "SUCCESS" ? 0 : 1);
        orderPay.setPayRemark(wxPayOrderNotifyResult.getReturnMsg());
        orderPay.setGmtCreate(new Date());
        orderPay.setGmtModified(new Date());
        orderPayMapper.insert(orderPay);
        logger.info("订单支付回调，正常完成，订单号：" + wxPayOrderNotifyResult.getAttach());
    }


    private void orderFightFailure(ShopProductStockManagerParam stockManagerParam) {
        //执行拼团失败
        UpdateWrapper<TownOrderFight> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("is_group", 1);
        updateWrapper.eq("is_delete", 0);
        updateWrapper.eq("order_status", 2);
        updateWrapper.eq("pay_status", 4);
        updateWrapper.eq("id", stockManagerParam.getOrderId());
        updateWrapper.set("order_status", 4);
        updateWrapper.set("is_success", 0);
        updateWrapper.set("success_time", LocalDateTime.now());
        updateWrapper.set("close_reason", "未在拼团限时时间内完成拼团。");
        orderFightMapper.update(new TownOrderFight(), updateWrapper);
        // TODO: 2018/11/18 需要执行退款
    }

    private void orderFightTimeOut(ShopProductStockManagerParam stockManagerParam) {
        //关闭订单，删除对应子订单
        QueryWrapper<TownOrderFight> orderQueryWrapper = new QueryWrapper<TownOrderFight>();
        orderQueryWrapper.eq("id", stockManagerParam.getOrderId());
        orderQueryWrapper.eq("order_number", stockManagerParam.getOrderNum());
        orderQueryWrapper.eq("is_delete", 0);
        TownOrderFight order = orderFightMapper.selectOne(orderQueryWrapper);
        if (order == null) {
            logger.error("拼团订单超时关闭，查询不到当前订单，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
            return;
        }
        Date date = new Date();
        if (order.getOrderStatus() == 1 && order.getPayStatus() == 1) {
            //订单已经到时间
            TownOrderFight orderUpadate = new TownOrderFight();
            orderUpadate.setId(order.getId());
            orderUpadate.setOrderStatus(8);
            orderUpadate.setCloseReason("超时未付款，订单已关闭");
            orderUpadate.setGmtModified(date);
            orderFightMapper.updateById(orderUpadate);
            //更新orderItems
            QueryWrapper<OrderItemsFight> itemsQueryWrapper = new QueryWrapper<OrderItemsFight>();
            itemsQueryWrapper.eq("order_id", stockManagerParam.getOrderId());
            itemsQueryWrapper.eq("is_delete", 0);
            List<OrderItemsFight> orderItemsList = orderItemsMapper.selectList(itemsQueryWrapper);
            if (orderItemsList == null || orderItemsList.isEmpty()) {
                logger.error("订单超时关闭，查询不到对应子订单，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
                return;
            }
            orderItemsList.stream().forEach(o -> {
                if (order.getIsGroup() == 0) {
                    this.shopProductFightSkuReturn(date, o);
                }
            });
        } else {
            logger.info("订单超时关闭，当前订单状态不符合关闭。订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
        }
    }

    private void orderFightStock(ShopProductStockManagerParam stockManagerParam) {
        QueryWrapper<TownOrderFight> orderQueryWrapper = new QueryWrapper<TownOrderFight>();
        orderQueryWrapper.eq("order_number", stockManagerParam.getOrderNum());
        orderQueryWrapper.eq("is_delete", 0);
        TownOrderFight order = orderFightMapper.selectOne(orderQueryWrapper);
        if (order == null) {
            logger.error("查询不到当前拼团订单，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
            return;
        } else {
            if (order.getPayStatus() != 4 && order.getOrderStatus() != 2) {
                logger.error("查询当前拼团订单状态错误，订单id:" + stockManagerParam.getOrderId() + ",支付状态：" + order.getPayStatus() + ",订单状态：" + order.getOrderStatus());
            }
        }

        if (order.getIsGroup() == 0) {
            //单独购买，直接扣除库存
            this.shopProductStockHandle(order, stockManagerParam);
        } else if (order.getIsGroup() == 1) {
            // 查询对应商品信息
            ShopProductFight shopProductFight = shopProductFightMapper.getShopProductByOrderFightId(order.getId());
            //当前是团长
            if (order.getParentId() == 0) {
                if (shopProductFight == null) {
                    logger.error("查询不到当前拼团商品，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
                    return;
                }
                TownOrderFight orderUpadate = new TownOrderFight();
                orderUpadate.setId(order.getId());
                orderUpadate.setOrderStatus(2);
                LocalDateTime endTime = LocalDateTime.now().plusHours(shopProductFight.getLimitTime());
                orderUpadate.setFightLastTime(DateUtils.localDateToDateTime(endTime));
                orderFightMapper.updateById(orderUpadate);
                String redisKey = MessageFormat.format(StringConstant.SHOP_PRODUCT_FIGHT_PART_COUNT, shopProductFight.getId());
                templateManager.getMasterTemplate().opsForHash().increment(redisKey, order.getId(), 1);
            } else {
                //当前是参团
                TownOrderFight parentTownOrderFight = orderFightMapper.selectById(order.getParentId());
                if (parentTownOrderFight == null) {
                    logger.error("查询不到当前参团团长订单，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
                    return;
                }
                //查询当前拼团数量是否足够
                List<Integer> partFightList = orderFightMapper.getOrderPartOrderId(parentTownOrderFight.getId());
                partFightList.add(parentTownOrderFight.getId());
                if (partFightList.size() + 1 >= parentTownOrderFight.getGroupNum()) {
                    //满足拼团
                    UpdateWrapper<TownOrderFight> fightUpdateWrapper = new UpdateWrapper<>();
                    fightUpdateWrapper.in("id", partFightList);
                    fightUpdateWrapper.set("order_status", 3);
                    fightUpdateWrapper.set("is_success", 1);
                    fightUpdateWrapper.set("join_group_num", partFightList.size() + 1);
                    fightUpdateWrapper.set("success_time", LocalDateTime.now());
                    int updateCount = orderFightMapper.update(new TownOrderFight(), fightUpdateWrapper);
                    if (updateCount > 0) {
                        String redisKey = MessageFormat.format(StringConstant.SHOP_PRODUCT_FIGHT_PART_COUNT, shopProductFight.getId());
                        //去除Redis记录
                        templateManager.getMasterTemplate().opsForHash().delete(redisKey, parentTownOrderFight.getId());
                        //库存修改
                        this.shopProductFightSuccessHandle(partFightList);
                    }
                } else {
                    TownOrderFight orderUpadate = new TownOrderFight();
                    orderUpadate.setId(order.getId());
                    orderUpadate.setOrderStatus(2);
                    orderUpadate.setFightLastTime(parentTownOrderFight.getFightLastTime());
                    orderFightMapper.updateById(orderUpadate);
                    UpdateWrapper<TownOrderFight> fightUpdateWrapper = new UpdateWrapper<>();
                    fightUpdateWrapper.in("id", partFightList);
                    fightUpdateWrapper.last("join_group_num = join_group_num+1");
                    orderFightMapper.update(new TownOrderFight(), fightUpdateWrapper);
                }
            }
        }
    }


    private void shopProductFightSuccessHandle(List<Integer> orderIdList) {
        QueryWrapper<OrderItemsFight> itemsQueryWrapper = new QueryWrapper<OrderItemsFight>();
        itemsQueryWrapper.in("order_id", orderIdList);
        itemsQueryWrapper.eq("is_delete", 0);
        List<OrderItemsFight> orderItemsFightList = orderItemsMapper.selectList(itemsQueryWrapper);
        if (orderItemsFightList == null || orderItemsFightList.isEmpty()) {
            logger.error("当前拼团成功子订单查询失败，订单id:" + orderIdList.toString());
            return;
        }
        for (OrderItemsFight orderItemsFight : orderItemsFightList) {
            //减少mongo库存
            UpdateOperations<ShopSkuModel> updateOperations = shopSkuModelDao.createUpdateOperations();
            updateOperations.dec("stock", orderItemsFight.getPurchaseQuantity());
            updateOperations.set("gmtModified", new Date());
            Query<ShopSkuModel> skuModelQuery = shopSkuModelDao.createQuery(ShopSkuModel.class);
            skuModelQuery.field("shopSpecificationSkuId").equal(orderItemsFight.getShopSpecificationSkuId());
            skuModelQuery.field("type").equal(2);
            int updateMongoCount = shopSkuModelDao.update(skuModelQuery, updateOperations).getUpdatedCount();
            if (updateMongoCount <= 0) {
                logger.error("拼团订单超时回mongo库存失败，商品主键id:" + orderItemsFight.getShopProductId() + ",回库数量：" + orderItemsFight.getPurchaseQuantity());
            }
            //减少Redis库存
            QueryWrapper<ShopSpecificationSku> skuQueryWrapper = new QueryWrapper<ShopSpecificationSku>();
            skuQueryWrapper.eq("id", orderItemsFight.getShopSpecificationSkuId());
            skuQueryWrapper.eq("sku_id", orderItemsFight.getShopSpecificationSkuSkuId());
            skuQueryWrapper.eq("type", 2);
            skuQueryWrapper.eq("is_deleted", 0);
            ShopSpecificationSku shopSpecificationSku = specificationSkuMapper.selectOne(skuQueryWrapper);
            if (shopSpecificationSku == null || shopSpecificationSku.getStock() < orderItemsFight.getPurchaseQuantity()) {
                createFailueOrder(orderItemsFight.getOrderId());
                logger.error("当前订单有商品库存不足，订单id:" + orderIdList.toString());
                continue;
            }
            //更新mysql信息
            UpdateWrapper<ShopSpecificationSku> skuUpdateWrapper = new UpdateWrapper<ShopSpecificationSku>();
            skuUpdateWrapper.setSql("stock = stock -" + orderItemsFight.getPurchaseQuantity());
            skuUpdateWrapper.eq("id", orderItemsFight.getShopSpecificationSkuId());
            skuUpdateWrapper.eq("sku_id", orderItemsFight.getShopSpecificationSkuSkuId());
            skuUpdateWrapper.eq("is_deleted", 0);
            skuUpdateWrapper.eq("type", 2);
            skuUpdateWrapper.ge("stock", 0);
            int updateCount = specificationSkuMapper.update(new ShopSpecificationSku(), skuUpdateWrapper);
            if (updateCount >= 1) {
                UpdateWrapper<ShopProductFight> updateWrapper = new UpdateWrapper<ShopProductFight>();
                updateWrapper.setSql("stock = stock - " + orderItemsFight.getPurchaseQuantity());
                updateWrapper.setSql("sale_count = sale_count + " + orderItemsFight.getPurchaseQuantity());
                updateWrapper.eq("id", orderItemsFight.getShopProductId());
                updateWrapper.ge("stock", 0);
                int shopCount = shopProductFightMapper.update(new ShopProductFight(), updateWrapper);
                if (shopCount <= 0) {
                    QueryWrapper<ShopProductFight> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("id", orderItemsFight.getShopProductId());
                    queryWrapper.select("id", "stock");
                    ShopProductFight shopProduct = shopProductFightMapper.selectOne(queryWrapper);
                    if (shopProduct != null) {
                        if (shopProduct.getStock() <= 0) {
                            //判断是否库存已经没了，修改状态为已售罄
                            UpdateWrapper<ShopProductFight> productUpdateWrapper = new UpdateWrapper<ShopProductFight>();
                            productUpdateWrapper.eq("id", shopProduct.getId());
                            productUpdateWrapper.ge("stock", 0);
                            productUpdateWrapper.set("sale_status", 1);
                            shopProductFightMapper.update(new ShopProductFight(), productUpdateWrapper);
                        }
                    }
                }
            }
        }

    }


    private void shopProductStockHandle(TownOrderFight order, ShopProductStockManagerParam stockManagerParam) {
        QueryWrapper<OrderItemsFight> itemsQueryWrapper = new QueryWrapper<OrderItemsFight>();
        itemsQueryWrapper.eq("order_id", order.getId());
        itemsQueryWrapper.eq("is_delete", 0);
        OrderItemsFight orderItemsFight = orderItemsMapper.selectOne(itemsQueryWrapper);
        if (orderItemsFight == null) {
            createFailueOrder(order.getId());
            logger.error("当前拼团订单无商品，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
            return;
        }
        QueryWrapper<ShopSpecificationSku> skuQueryWrapper = new QueryWrapper<ShopSpecificationSku>();
        skuQueryWrapper.eq("id", orderItemsFight.getShopSpecificationSkuId());
        skuQueryWrapper.eq("sku_id", orderItemsFight.getShopSpecificationSkuSkuId());
        skuQueryWrapper.eq("type", 2);
        skuQueryWrapper.eq("is_deleted", 0);
        ShopSpecificationSku shopSpecificationSku = specificationSkuMapper.selectOne(skuQueryWrapper);
        if (shopSpecificationSku == null || shopSpecificationSku.getStock() < orderItemsFight.getPurchaseQuantity()) {
            createFailueOrder(order.getId());
            logger.error("当前订单有商品库存不足，订单id:" + stockManagerParam.getOrderId() + ",订单流水号：" + stockManagerParam.getOrderNum());
            return;
        }
        //更新mysql信息
        UpdateWrapper<ShopSpecificationSku> skuUpdateWrapper = new UpdateWrapper<ShopSpecificationSku>();
        skuUpdateWrapper.setSql("stock = stock -" + orderItemsFight.getPurchaseQuantity());
        skuUpdateWrapper.eq("id", orderItemsFight.getShopSpecificationSkuId());
        skuUpdateWrapper.eq("sku_id", orderItemsFight.getShopSpecificationSkuSkuId());
        skuUpdateWrapper.eq("is_deleted", 0);
        skuUpdateWrapper.eq("type", 2);
        skuUpdateWrapper.ge("stock", 0);
        int updateCount = specificationSkuMapper.update(new ShopSpecificationSku(), skuUpdateWrapper);
        if (updateCount >= 1) {
            UpdateWrapper<ShopProductFight> updateWrapper = new UpdateWrapper<ShopProductFight>();
            updateWrapper.setSql("stock = stock - " + orderItemsFight.getPurchaseQuantity());
            updateWrapper.setSql("sale_count = sale_count + " + orderItemsFight.getPurchaseQuantity());
            updateWrapper.eq("id", orderItemsFight.getShopProductId());
            updateWrapper.ge("stock", 0);
            int shopCount = shopProductFightMapper.update(new ShopProductFight(), updateWrapper);
            if (shopCount <= 0) {
                QueryWrapper<ShopProductFight> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id", orderItemsFight.getShopProductId());
                queryWrapper.select("id", "stock");
                ShopProductFight shopProduct = shopProductFightMapper.selectOne(queryWrapper);
                if (shopProduct != null) {
                    if (shopProduct.getStock() <= 0) {
                        //判断是否库存已经没了，修改状态为已售罄
                        UpdateWrapper<ShopProductFight> productUpdateWrapper = new UpdateWrapper<ShopProductFight>();
                        productUpdateWrapper.eq("id", shopProduct.getId());
                        productUpdateWrapper.ge("stock", 0);
                        productUpdateWrapper.set("sale_status", 1);
                        shopProductFightMapper.update(new ShopProductFight(), productUpdateWrapper);
                    }
                }
            }
        }
        //更新订单状态
        TownOrderFight orderNew = new TownOrderFight();
        orderNew.setId(order.getId());
        orderNew.setGmtModified(new Date());
        orderNew.setOrderStatus(5);
        orderFightMapper.updateById(orderNew);
    }


    private void shopProductFightSkuReturn(Date date, OrderItemsFight o) {
        UpdateOperations<ShopSkuModel> updateOperations = shopSkuModelDao.createUpdateOperations();
        updateOperations.inc("stock", o.getPurchaseQuantity());
        updateOperations.set("gmtModified", date);
        Query<ShopSkuModel> skuModelQuery = shopSkuModelDao.createQuery(ShopSkuModel.class);
        skuModelQuery.field("shopSpecificationSkuId").equal(o.getShopSpecificationSkuId());
        skuModelQuery.field("type").equal(2);
        int updateCount = shopSkuModelDao.update(skuModelQuery, updateOperations).getUpdatedCount();
        if (updateCount <= 0) {
            logger.error("拼团订单超时回mongo库存失败，商品主键id:" + o.getShopProductId() + ",回库数量：" + o.getPurchaseQuantity());
        }
    }


    private void createFailueOrder(Integer orderId) {
        TownOrderFight orderNew = new TownOrderFight();
        orderNew.setOrderStatus(6);
        orderNew.setId(orderId);
        orderNew.setGmtModified(new Date());
        orderNew.setCloseReason("商品出库失败");
        orderFightMapper.updateById(orderNew);
        // TODO: 2018/11/4 后续补回走退款流程
    }
}
